'use strict';

const fs = require('fs')
const router = require('koa-router')()

function getRouterFile(filePath){
    let filePaths = filePath || __dirname

    let files = fs.readdirSync(filePaths)

    let routerFiles = files.filter(item=>{
        return item.endsWith('.js') && item !== 'index.js'
    })

    return routerFiles;
}



function registerRouterFile(routerFiles,router){
    routerFiles.forEach(item=>{
        let temPath = __dirname + '/' + item

        let obj = require(temPath)

        for(let key in obj){
            let temPath = key.split(' ')

            let routerMethor = temPath[0]
            let routerUrl = temPath[1]
            let routerFunction = obj[key]
            
            if(routerMethor === 'get'){
                router.get(routerUrl,routerFunction)
            }else if(routerMethor === 'post'){
                router.post(routerUrl,routerFunction)
            }else if(routerMethor === 'put'){
                router.put(routerUrl,routerFunction)
            }else if(routerMethor === 'delete'){
                router.delete(routerUrl,routerFunction)
            }else{

            }
        }
    })
    return router.routes();
}

module.exports = function(){
    let routerFiles = getRouterFile();
    let fn = registerRouterFile(routerFiles,router);
    return fn;
}